//
//  HumanResourceViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/12/12.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class HumanResourceViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {

    var father: NewAnalysisContainerViewController?
    
    var source: [JSON] = []
    
    let header = Bundle.main.loadNibNamed("HumanResourceHeader", owner: nil, options: nil)?[0] as? UIView
    
    let footer = Bundle.main.loadNibNamed("HumanResourceFooter", owner: nil, options: nil)?[0] as? HumanResourceFooter
    
    override var names: Array<String>{
        get{
            return ["GETORG","HUMANRESOURCE"]
        }
    }
    
    override func path(for name: String) -> String {
        if name == "GETORG" {
            return GETORG
        }
        return HumanResource
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.father!.view.endEditing(true)
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        if name == "GETORG" {
            return [:]
        } else {
            return ["orgcode": selectedCompany,"searchDate": self.father!.endDate()]
        }
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override func success(for name: String) -> NetSuccess {
        func orgcode(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    companys = data
                    if companys.count > 0 {
                        let item = self.companys[0]
                        self.selectedCompany = item.contents!["code"]!.rawString()!
                        self.companyField.text = item.contents?["name"]?.rawString()
                        self.load(with: self.names[1])
                    }
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        func human(json: JSON)->Void{
            if let data = json.contents?["data"]?.array {
                self.source = data
                self.tableView.reloadData()
            }
        }
        if name == names[0] {
            return orgcode
        } else {
            return human
        }
    }
    
    @objc func dateChange(not: Notification){
        self.load(with: "HUMANRESOURCE")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(dateChange(not:)), name: NSNotification.Name("DateChange"), object: nil)
        let tbheader = UIView()
        tbheader.frame = CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 30))
        tbheader.backgroundColor = .white
        let label = UILabel()
        label.text = "金额单位: 万元"
        label.textColor = UIColor.init(red: 73 / 255, green: 142 / 255, blue: 226 / 255, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 14)
        let size = label.text!.size(with: label.font)
        label.frame = CGRect.init(origin: CGPoint.init(x: 15, y: tbheader.height * 0.5 - size.height / 2), size: size)
        tbheader.addSubview(label)
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.tableHeaderView = tbheader
        self.tableView.separatorStyle = .none
        self.tableView.register(UINib.init(nibName: "ChartCell", bundle: Bundle.main), forCellReuseIdentifier: "ChartCell")
        self.tableView.register(UINib.init(nibName: "HumanResourceCell", bundle: Bundle.main), forCellReuseIdentifier: "HumanResourceCell")
        self.load(with: names[0])
    }
    
    var companys: [JSON] = []
    
    var selectedCompany = ""
    
    func popalert() -> Void {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item.contents?["code"]?.rawString() ?? ""
                
                self.load(with: self.names[1])
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    var chartheight: CGFloat = 250.0
    
    var rowheight: CGFloat {
        get{
            return (self.tableView.height - chartheight) / CGFloat((self.tableView(tableView, numberOfRowsInSection: 0) + 3))
        }
    }
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var companyField: UITextField!
    
    @IBAction func showAlertAction(_ sender: Any) {
        self.popalert()
    }
}

extension HumanResourceViewController{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            return tableView.dequeueReusableCell(withIdentifier: "HumanResourceCell")!
        default:
            return tableView.dequeueReusableCell(withIdentifier: "ChartCell")!
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        switch section {
        case 0:
            return self.source.count
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return rowheight
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 0:
            return header
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let cel = cell as? HumanResourceCell {
            cel.model = self.source[indexPath.row]
            if indexPath.row % 2 == 0 {
                cel.contentView.backgroundColor = UIColor.white
            } else {
                cel.contentView.backgroundColor = UIColor.hex("F4F7F9")
            }
        }
        if let cel = cell as? ChartCell {
            //填入数据
            cel.source = self.source
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return rowheight
        default:
            return 0
        }
    }
    
    var mans: Int{
        get{
            return source.reduce(0, { (result, json) -> Int in
                return result + (json.contents?["personAmount"]?.int ?? 0)
            })
        }
    }//人数总计
    
    var totalcosts: Int{
        get{
            return source.reduce(0, { (result, json) -> Int in
                return result + (json.contents?["totalAmount"]?.int ?? 0) / 1000000
            })
        }
    }//人工总成本
    
    var totalsalary: Int{
        get{
            return source.reduce(0, { (result, json) -> Int in
                return result + (json.contents?["salaryAmount"]?.int ?? 0) / 1000000
            })
        }
    }//工资总额
    
    var soceityfinacial: Int{
        get{
            return source.reduce(0, { (result, json) -> Int in
                return result + (json.contents?["otherAmount"]?.int ?? 0) / 1000000
            })
        }
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch section {
        case 0:
            footer?.humansLabel.text = String(mans)
            footer?.humansCostLabel.text = String(totalcosts)
            footer?.salaryLabel.text = String(totalsalary)
            footer?.soceityLabel.text = String(soceityfinacial)
            return footer
        default:
            return nil
        }
    }

    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0:
            return rowheight
        default:
            return chartheight
        }
    }
}
